package com.graduate.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.db.pojo.Information;
import com.graduate.exception.BizException;
import com.graduate.exception.ExceptionEnum;
import com.graduate.service.AsyncService;
import com.graduate.service.InformationService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;

import java.text.SimpleDateFormat;
import java.util.*;

public abstract class BaseServiceUtils {
    //日志打印器
    protected Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    protected InformationService informationService;
    @Autowired
    protected AsyncService asyncService;
//    protected Map<String, Object> responseMap = new HashMap<>();

    //获得单表信息
    public Information getInformationService(String table) {
        Information information = informationService.getInformation(table);
        return information;
    }

    //获得所有表信息
    public List<Information> getInformationListService() {
        List<Information> informationList = informationService.getInformationList();
        return informationList;
    }

    //字符串转Map
    public List<String> stringToList(String str) {

        List<String> list = new ArrayList<>();
        String split[] = str.split(",");
        for (int i = 0; i < split.length; i++) {
            list.add(split[i]);
        }
        return list;
    }

    //Json转map
    public Map<String, Object> jsonToMap(String str) {
        JSONObject obj = JSON.parseObject(str);
        Map<String, Object> data = new HashMap<>();
        //循环转换
        Iterator it = obj.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry<String, Object> entry = (Map.Entry<String, Object>) it.next();
            data.put(entry.getKey(), entry.getValue());
        }
        return data;
    }

    public int updateIndex(String table, int index, int update_index) {
        int ret = informationService.updateIdIndex(table, index, update_index);
        return ret;
    }

    /*@RequestMapping(value = "/insertRecords", method = RequestMethod.POST)
    @Transactional*/
    public String insertRecords(Map<String, Object> requesetMap) {
        String table = "records";
        Information information = getInformationService(table);
        int index = information.getID_INDEX();
        String pr = information.getID_PREFIX();
        int length = information.getID_LENGTH();
        String id = generateId(pr, length, index);
        String fieldsValue = "";
        fieldsValue += "'" + id + "'," + "'" + requesetMap.get("associator") + "'," + "'" + requesetMap.get("openid") + "',"
                + "'" + requesetMap.get("op_desc") + "'," + "'" + requesetMap.get("op_type") + "'" +
                (StringUtils.isEmpty(requesetMap.get("article")) ? ",''" : ",'" + requesetMap.get("article") + "'");
        informationService.insertRecords(fieldsValue);
        int update_index = (index + 1) % 1000000;
        updateIndex(table, index, update_index);
        return id;
    }

    //id生成策略
    public String generateId(String prefix, int length, int index) {
        java.util.Date now = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmm");
        String nowDate = sdf.format(now);
        int mx = length - nowDate.length() - prefix.length();
        return prefix + nowDate + String.format("%0" + mx + "d", index);
    }


    public String insert(Map<String, Object> requesetMap) {
        String table = (String) requesetMap.get("table");
        Information information = getInformationService(table);
        int index = information.getID_INDEX();
        String pr = information.getID_PREFIX();
        int length = information.getID_LENGTH();
        String id = generateId(pr, length, index);
        String fileds = information.getFIELDS_NAME();
        List<String> fieldsList = stringToList(fileds);
        String fieldsName = "";
        String fieldsValue = "";
        for (int i = 0; i < fieldsList.size(); i++) {
            String fields = fieldsList.get(i);
            if (requesetMap.containsKey(fields)) {
                fieldsName += fields + ",";
                fieldsValue += "'" + requesetMap.get(fields) + "',";
            }
        }
        fieldsName += "id";
        fieldsValue += "'" + id + "'";
        int ret = informationService.insertTable(table, fieldsName, fieldsValue);
        if (ret <= 0) {
            throw new BizException(ExceptionEnum.INTERNAL_SERVER_ERROR);
        }
        int update_index = (index + 1) % 1000000;
        ret = updateIndex(table, index, update_index);
        if (ret <= 0) {
            throw new BizException(ExceptionEnum.INTERNAL_SERVER_ERROR);
        }
        return id;
    }

    public int update(String id, Map<String, String> requestMap) {
        String table = requestMap.get("table");
        Information information = getInformationService(table);
        String fileds = information.getFIELDS_NAME();
        List<String> fieldsList = stringToList(fileds);
        String setSql = "";
        for (int i = 0; i < fieldsList.size(); i++) {
            String fields = fieldsList.get(i);
            if (requestMap.containsKey(fields)) {
                setSql += fields + "='" + requestMap.get(fields) + "',";
            }
        }
        setSql = setSql.substring(0, setSql.length() - 1);
        int ret = informationService.updateTable(table, setSql, id);
        if (ret <= 0) {
            throw new BizException("500", "更新数据失败");
        }

        return ret;
    }


    public int delete(String id, Map<String, String> requestMap) {
        String table = requestMap.get("table");
        String setSql = "state=1";
        setSql = setSql.substring(0, setSql.length() - 1);
        int ret = informationService.updateTable(table, setSql, id);
        if (ret <= 0) {
            throw new BizException("500", "更新数据失败");
        }

        return ret;
    }

    public List<Map<String, Object>> selectList(Map<String, Object> requesetMap) {
        String table = (String) requesetMap.get("table");
        String fieldsName = (String) requesetMap.get("fieldsName");
        if (StringUtils.isEmpty(fieldsName)) {
            fieldsName = "*";
        }
        Information information = getInformationService(table);
        String queryMsg = "";
        String fileds = information.getFIELDS_NAME();
        List<String> fieldsList = stringToList(fileds);
        for (int i = 0; i < fieldsList.size(); i++) {
            String fields = fieldsList.get(i);
            if (requesetMap.containsKey(fields)) {
                String fieldsValue = (String) requesetMap.get(fields);
                switch (fieldsValue.charAt(0)) {
                    case '{':
                        queryMsg += " AND " + fields + " in ('" + fieldsValue.substring(1).replaceAll(",", "','") + "')";
                        break;
                    case '~':
                        queryMsg += " AND " + fields + " like '" + fieldsValue.substring(1) + "'";
                        break;
                    case '!':
                        switch (fieldsValue.charAt(1)) {
                            case '<':
                                queryMsg += " AND " + fields + ">='" + fieldsValue + "'";
                                break;
                            case '>':
                                queryMsg += " AND " + fields + "<='" + fieldsValue + "'";
                                break;
                            default:
                                queryMsg += " AND " + fields + "!='" + fieldsValue + "'";
                                break;
                        }
                        break;
                    case '<':
                        queryMsg += " AND " + fields + "<'" + fieldsValue.substring(1) + "'";
                        break;
                    case '>':
                        queryMsg += " AND " + fields + ">'" + fieldsValue.substring(1) + "'";
                        break;
                    default:
                        queryMsg += " AND " + fields + "='" + fieldsValue + "'";
                        break;
                }
            }
        }
        String sort = (String) requesetMap.get("sort");
        if (!StringUtils.isEmpty(sort)) {
            if (sort.charAt(0) == '-') {
                queryMsg += " ORDERY BY " + sort.substring(1) + " DESC";
            } else {
                queryMsg += " ORDERY BY " + sort;
            }

        }
        String limit = (String) requesetMap.get("limit");
        if (!StringUtils.isEmpty(limit)) {
            queryMsg += " LIMIT " + limit;
        }
        String offset = (String) requesetMap.get("offset");
        if (!StringUtils.isEmpty(offset)) {
            queryMsg += " OFFSET " + offset;
        }
        List<Map<String, Object>> resultList = informationService.selectTableList(table, fieldsName, queryMsg);
        return resultList;
    }

    public Map<String, Object> select(String id, String table, String fieldsMsg) {
        if (StringUtils.isEmpty(fieldsMsg)) {
            fieldsMsg = "*";
        }
        Map<String, Object> responseMap = informationService.selectTable(table, id, fieldsMsg);
        return responseMap;
    }

}
